package com.lnsf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lnsf.dao.ISupplierDao;
import com.lnsf.dbutils.DataAccess;
import com.lnsf.model.Supplier;

public class SupplierDaoImpl implements ISupplierDao {

	@Override
	public List<Supplier> select() {
		List<Supplier> list = new ArrayList<Supplier>();
		Connection conn = null;
		PreparedStatement prep = null;
		ResultSet rs = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("select * from supplier");
			rs = prep.executeQuery();
			while (rs.next()) {
				Supplier supplier = new Supplier(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getFloat(4),
						rs.getInt(5));
				list.add(supplier);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(rs, prep, conn);
		}
		return list;
	}

	@Override
	public int insert(Supplier supplier) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("insert into supplier values (null, ?, ?, ?,?)");
			prep.setInt(1, supplier.getuId());
			prep.setString(2, supplier.getgName());
			prep.setFloat(3, supplier.getSuppPrice());
			prep.setInt(4, supplier.getSuppNum());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

	@Override
	public int update(Supplier supplier) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("update supplier set uId = ?,gName=?, suppPrice=?,suppNum=? where suId = ?");
			prep.setInt(1, supplier.getuId());
			prep.setString(2, supplier.getgName());
			prep.setFloat(3, supplier.getSuppPrice());
			prep.setInt(4, supplier.getSuppNum());
			prep.setInt(5, supplier.getSuId());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

	@Override
	public int delete(Supplier supplier) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("delete from supplier where suId = ?");
			prep.setInt(1, supplier.getSuId());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

}
